package com.deep.transaction.demo.service;

import com.deep.transaction.demo.entity.Staff;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StaffService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public void insert(List<Staff> Staffs) {

        for (Staff staff : Staffs) {
            System.out.println("Inserting Data for Staff name: " + staff.getName());
            jdbcTemplate.update("insert into Staff(Name, Dept, Salary) values (?, ?, ?)",
                    preparedStatement -> {
                        preparedStatement.setString(1, staff.getName());
                        preparedStatement.setString(2, staff.getDept());
                        preparedStatement.setLong(3, staff.getSalary());
                    });
        }
    }

    public List<Staff> getStaffs() {
        System.out.println("Retrieve all Staffs List...");
        List<Staff> staffList = jdbcTemplate.query("select Name, Dept, Salary from Staff", (resultSet, i) -> new Staff(resultSet.getString("Name"),
                resultSet.getString("Dept"),
                resultSet.getLong("Salary")));

        return staffList;
    }

}
